// @Description 延时任务服务层
// @Author  xiaoyang
// @Date  2025/11/26

package services

import (
	"errors"
	"golang-manage-admin/http/modules/demo/dao"
	"golang-manage-admin/http/modules/demo/dto"
	"golang-manage-admin/lib"
	"golang-manage-admin/providers"
	"golang-manage-admin/queue/publish"
	"strconv"
)

// DelayedService 延时任务服务
type DelayedService struct {
	Service
}

// SendDelayedTask 添加延时任务
// 将延时任务保存到数据库并推送到消息队列
func (s *DelayedService) SendDelayedTask(form *dto.SendDelayedTaskForm) error {
	// 生成任务ID
	form.TaskId = lib.GenerateID()

	providers.Logger.Debugf("添加延时任务--接收消息体成功: %+v", form)

	// 获取数据库连接
	tx := providers.Mysqls["task"]
	if tx == nil {
		return errors.New("数据库连接失败")
	}

	// 保存到数据库
	delayedQueueDao := dao.NewDelayedQueueDao()
	expires, err := strconv.Atoi(form.Expires)
	if err != nil {
		return errors.New("过期时间格式错误")
	}

	saveErr := delayedQueueDao.SaveDelayedQueue(tx, &dao.DelayedQueue{
		TaskId:     form.TaskId,
		TaskName:   form.TaskName,
		FromSystem: form.FromSystem,
		FromApi:    form.FromApi,
		Expires:    expires,
		Detail:     form.Detail,
		Data:       form.Data,
	})

	if saveErr != nil {
		return saveErr
	}

	// 推送到消息队列
	pushErr := publish.PublishObject.PushFormatDelayed(publish.CDelayed, form, form.Expires)
	if pushErr != nil {
		_ = providers.Logger.Errorf("推送消息接收队列失败Error:%s, Content:%+v", pushErr.Error(), form)
		return pushErr
	}

	providers.Logger.Debugf("消息接收消息体推送队列成功: %+v", form)
	return nil
}
